﻿//        Another Demo from Andy L. & MissedMemo.com
// Borrow whatever code seems useful - just don't try to hold
// me responsible for any ill effects. My demos sometimes use
// licensed images which CANNOT legally be copied and reused.

using System;
using System.ComponentModel;
using System.Windows.Threading;


namespace MissedMemo.MeatAndCheeseDisc.UIHelperClasses
{
    public class OrderTimer : INotifyPropertyChanged
    {
        private Nullable<DateTime> _datetimeStartProcessing = null;
        private bool _isRunning;

        public static TimeSpan ScheduleWarningThreshold = TimeLimitLookup.GetLimit( "WarningThreshold" );
        public static TimeSpan ScheduleErrorThreshold = TimeLimitLookup.GetLimit( "ErrorThreshold" );
        
        // Share a SINGLE timer among all orders
        private static DispatcherTimer _sharedTimer = new DispatcherTimer();

        public event PropertyChangedEventHandler PropertyChanged;
        public event EventHandler Tick;


    #region Properties...

        public TimeSpan ElapsedTime
        {
            get
            {
                if( _isRunning )
                    return DateTime.Now - _datetimeStartProcessing.Value;
                else
                    return TimeSpan.Zero;
            }

            // No setter: Timer's call to 'Notify' causes clients
            // to reference calculated value in getter above.
        }

    #endregion (Properties)


        public OrderTimer()
        {
            if( _sharedTimer.IsEnabled == false )
                _sharedTimer.Start();

            _sharedTimer.Tick += OnSharedTimerTick;
        }


        public void BeginTracking()
        {
            if( false == _datetimeStartProcessing.HasValue )
                _datetimeStartProcessing = DateTime.Now;

            _isRunning = true;
        }


        public void SuspendTracking()
        {
            _isRunning = false;
        }


        void OnSharedTimerTick( object sender, EventArgs e )
        {
            if( Tick != null )
                Tick( this, EventArgs.Empty );

            Notify( "ElapsedTime" );
        }


        private void Notify( string strNotification )
        {
            if( PropertyChanged != null )
            {
                PropertyChanged( this, new PropertyChangedEventArgs( strNotification ) );
            }
        }
    }
}
